#include <stdio.h>
#include <string.h>
#include <mysql/mysql.h>

#define HOST "127.0.0.1"
#define USERNAME "root"
#define PASSWORD "Wyn15598303669926492"
#define DBNAME "gobang"
#define PORT 3306

int main()
{
    //1.初始化mysql的操作句柄 MYSQL *mysql_init(MYSQL *mysql); -> 在堆上申请空间并初始化一个MySQL的操作句柄，然后返回该句柄的起始地址
    MYSQL* mysql = mysql_init(NULL);
    if(mysql == NULL)
    {
        printf("mysql init failed!!\n");
        return -1;
    }
    //2.连接mysql服务器(出于数据库的安全考虑，mysql只允许本地登录，不允许用公网ip远程登录)
    // MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd,const char *db, unsigned int
    //                           port,const char *unix_socket, unsigned long client_flag);
    if(mysql_real_connect(mysql, HOST, USERNAME, PASSWORD, DBNAME, PORT, NULL, 0) == NULL)
    {
        printf("connect mysql server failed: %s\n", mysql_error(mysql));
        mysql_close(mysql);//防止内存泄露
        return -1;
    }
    //3.设置当前客户端的字符集，保证和mysqld服务端的字符集一致 int mysql_set_character_set(MYSQL *mysql, const char *csname)
    if(mysql_set_character_set(mysql, "utf8") != 0)
    {
        printf("set client character failed: %s\n", mysql_error(mysql));
        mysql_close(mysql);//防止内存泄露
        return -1;
    }
    //4.选择要操作的数据库database(我们已经选择过了，这里什么都不做) int mysql_select_db(MYSQL *mysql, const char *db)
    // mysql_select_db(mysql, DBNAME);
    
    //5.开始执行sql语句
    
    // int mysql_query(MYSQL *mysql, const char *stmt_str)
    // char* sql = "insert into stu values (null, '张三', 18, 99, 101, 111);";
    // char* sql = "update stu set ch=ch+30 where id=1;";//错误sql语句示范
    // char* sql = "update stu set ch=ch+30 where sn=1;";
    // char* sql = "delete from stu where sn=2;";
    char* sql = "select * from stu;";

    int ret = mysql_query(mysql, sql);
    if(ret != 0)
    {
        printf("%s sql query failed: %s\n", sql, mysql_error(mysql));
        mysql_close(mysql);//防止内存泄露
        return -1;        
    }
    //5.1 若sql是查询语句，则需要保存查询结果到本地的结果集中  MYSQL_RES *mysql_store_result(MYSQL *mysql)
    MYSQL_RES *res = mysql_store_result(mysql);
    if(res == NULL) 
    {
        mysql_close(mysql);//防止内存泄露
        return -1;         
    }
    //5.2 获取结果集中的结果条数
    // uint64_t mysql_num_rows(MYSQL_RES *result); unsigned int mysql_num_fields(MYSQL_RES *result);
    int numRow = mysql_num_rows(res);
    int numCol = mysql_num_fields(res);
    //5.3 遍历保存到本地的结果集  MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
    for(int i = 0; i < numRow; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);//返回的row是一个char*数组，每个char*就是当前这行的各个列字段值
        for(int j = 0; j < numCol; j++) printf("%s\t", row[j]);
        printf("\n");
    }
    //5.4 释放结果集  void mysql_free_result(MYSQL_RES *result);
    mysql_free_result(res);

    //6.关闭mysql连接，释放操作句柄
    mysql_close(mysql);
    return 0;
}